import { reactive, computed } from 'vue'
import { 
  deviceAPI, 
  realDeviceAPI, 
  smartLightAPI, 
  smartThermostatAPI, 
  smartCameraAPI,
  deviceStatusAPI 
} from '../services/api.js'
import { useAuthStore } from './authStore.js'
import {
  LightDevice,
  AirConditionerDevice,
  CurtainDevice,
  CameraDevice,
  DEVICE_TYPES,
  DEVICE_STATUS,
  SCENE_MODES
} from '../types/device.js'

// 设备存储状态
const state = reactive({
  devices: [],
  currentScene: SCENE_MODES.HOME,
  deviceIdCounter: 1,
  loading: false,
  error: null,
  recentActivities: [] // 真实的活动记录
})

// 设备管理方法
export const useDeviceStore = () => {
  const authStore = useAuthStore()
  
  // 添加活动记录
  const addActivity = (message, type = 'info') => {
    const activity = {
      message,
      timestamp: new Date().toLocaleString('zh-CN'),
      type
    }
    state.recentActivities.unshift(activity)
    // 只保留最近20条记录
    if (state.recentActivities.length > 20) {
      state.recentActivities = state.recentActivities.slice(0, 20)
    }
  }
  
  // 加载用户设备
  const loadUserDevices = async () => {
    if (!authStore.isLoggedIn.value) return
    
    state.loading = true
    state.error = null
    
    try {
      console.log('开始加载用户设备，用户ID:', authStore.user.value.id)
      const devices = await deviceAPI.getUserDevices(authStore.user.value.id)
      console.log('获取到设备数据:', devices)
      console.log('设备数据类型:', typeof devices)
      console.log('是否为数组:', Array.isArray(devices))
      
      // 如果返回空数组，说明用户没有设备
      if (Array.isArray(devices) && devices.length === 0) {
        console.log('用户没有设备，初始化为空数组')
        state.devices = []
        return
      }
      
      if (!Array.isArray(devices)) {
        console.error('设备数据不是数组格式:', devices)
        throw new Error('设备数据格式错误，期望数组但得到: ' + typeof devices)
      }
      
      const detectTypeFromProperties = (rawProps) => {
        let props = {}
        try {
          props = typeof rawProps === 'string' ? JSON.parse(rawProps) : (rawProps || {})
        } catch (e) {
          // 属性不是JSON或解析失败，无法根据属性判断类型
          return null
        }
        if (props && (props.temperature !== undefined || props.mode !== undefined || props.fanSpeed !== undefined)) {
          return DEVICE_TYPES.AIR_CONDITIONER
        }
        if (props && props.position !== undefined) {
          return DEVICE_TYPES.CURTAIN
        }
        if (props && (props.brightness !== undefined || props.color !== undefined)) {
          return DEVICE_TYPES.LIGHT
        }
        if (props && (props.recording !== undefined || props.pan !== undefined || props.tilt !== undefined || props.resolution !== undefined)) {
          return DEVICE_TYPES.CAMERA
        }
        return null
      }

      const ensureDefaultsForType = (obj, type) => {
        if (type === DEVICE_TYPES.LIGHT) {
          if (obj.brightness === undefined) obj.brightness = 50
          if (obj.color === undefined) obj.color = '#ffffff'
          delete obj.temperature; delete obj.mode; delete obj.fanSpeed; delete obj.position
          delete obj.recording; delete obj.pan; delete obj.tilt; delete obj.resolution; delete obj.streamUrl
        } else if (type === DEVICE_TYPES.AIR_CONDITIONER) {
          if (obj.temperature === undefined) obj.temperature = 26
          if (obj.mode === undefined) obj.mode = 'cool'
          if (obj.fanSpeed === undefined) obj.fanSpeed = 'medium'
          delete obj.brightness; delete obj.color; delete obj.position
          delete obj.recording; delete obj.pan; delete obj.tilt; delete obj.resolution; delete obj.streamUrl
        } else if (type === DEVICE_TYPES.CURTAIN) {
          if (obj.position === undefined) obj.position = 0
          delete obj.brightness; delete obj.color; delete obj.temperature; delete obj.mode; delete obj.fanSpeed
          delete obj.recording; delete obj.pan; delete obj.tilt; delete obj.resolution; delete obj.streamUrl
        } else if (type === DEVICE_TYPES.CAMERA) {
          if (obj.recording === undefined) obj.recording = false
          if (obj.nightVision === undefined) obj.nightVision = false
          if (obj.resolution === undefined) obj.resolution = '1080p'
          if (obj.pan === undefined) obj.pan = 0
          if (obj.tilt === undefined) obj.tilt = 0
          if (obj.streamUrl === undefined) obj.streamUrl = ''
          delete obj.brightness; delete obj.color; delete obj.temperature; delete obj.mode; delete obj.fanSpeed; delete obj.position
        }
      }

      state.devices = devices.map((device, index) => {
        console.log(`处理设备 ${index + 1}:`, device)
        console.log('设备类型ID:', device.deviceTypeId)
        
        // 根据设备类型创建对应的设备对象
        let deviceType = getDeviceTypeById(device.deviceTypeId)
        const hintedType = detectTypeFromProperties(device.properties)
        if (hintedType && hintedType !== deviceType) {
          console.warn(`设备${device.id}属性与类型不一致，依据属性修正类型: ${deviceType} -> ${hintedType}`)
          deviceType = hintedType
        }
        console.log('映射后的设备类型:', deviceType)
        
        let deviceObj
        
        switch (deviceType) {
          case DEVICE_TYPES.LIGHT:
            deviceObj = new LightDevice(device.id, device.name, device.room)
            break
          case DEVICE_TYPES.AIR_CONDITIONER:
            deviceObj = new AirConditionerDevice(device.id, device.name, device.room)
            break
          case DEVICE_TYPES.CURTAIN:
            deviceObj = new CurtainDevice(device.id, device.name, device.room)
            break
          case DEVICE_TYPES.CAMERA:
            deviceObj = new CameraDevice(device.id, device.name, device.room)
            break
          default:
            console.warn('未知设备类型，使用默认灯光设备:', deviceType)
            deviceObj = new LightDevice(device.id, device.name, device.room)
        }
        
        // 设置设备状态和属性
        deviceObj.status = device.status === 1 ? DEVICE_STATUS.ON : DEVICE_STATUS.OFF
        if (device.properties) {
          try {
            const props = JSON.parse(device.properties)
            Object.assign(deviceObj, props)
          } catch (parseError) {
            console.warn('解析设备属性失败:', parseError)
          }
        }
        // 按最终类型补齐默认值并剔除无关属性，避免展示错位的控件
        ensureDefaultsForType(deviceObj, deviceType)
        
        return deviceObj
      })
      
      console.log('设备加载成功，共', state.devices.length, '个设备')
    } catch (error) {
      console.error('加载设备失败:', error)
      console.error('错误详情:', {
        message: error.message,
        name: error.name,
        stack: error.stack
      })
      
      // 如果是网络错误，提供更友好的提示
      if (error.message.includes('网络连接中断')) {
        state.error = '网络连接不稳定，请检查网络连接后重试'
      } else if (error.message.includes('无法连接到后端服务器')) {
        state.error = '后端服务未启动，请启动后端服务'
      } else if (error.message.includes('Failed to fetch')) {
        state.error = '后端服务未启动，请启动后端服务'
      } else if (error.message.includes('ERR_INCOMPLETE_CHUNKED_ENCODING')) {
        state.error = '网络连接中断，请检查网络连接或稍后重试'
      } else if (error.message.includes('HTTP 404')) {
        state.error = '设备API端点不存在，请检查后端服务配置'
      } else if (error.message.includes('HTTP 500')) {
        state.error = '后端服务器内部错误，请稍后重试'
      } else {
        state.error = `加载设备失败: ${error.message}`
      }
      
      // 后端服务不可用时，保持设备列表为空
      console.log('后端服务不可用，设备列表保持为空')
      state.devices = []
    } finally {
      state.loading = false
    }
  }
  
  // 根据设备类型ID获取类型名称
  const getDeviceTypeById = (typeId) => {
    // 这里需要根据后端返回的设备类型ID映射到前端类型
    // 设备类型ID映射：1-灯光，2-空调，3-窗帘，4-摄像头
    const typeMap = {
      1: DEVICE_TYPES.LIGHT,
      2: DEVICE_TYPES.AIR_CONDITIONER,
      3: DEVICE_TYPES.CURTAIN,
      4: DEVICE_TYPES.CAMERA,
      // 也支持字符串类型的映射
      'light': DEVICE_TYPES.LIGHT,
      'air_conditioner': DEVICE_TYPES.AIR_CONDITIONER,
      'curtain': DEVICE_TYPES.CURTAIN,
      'camera': DEVICE_TYPES.CAMERA
    }
    return typeMap[typeId] || DEVICE_TYPES.LIGHT
  }
  
  // 添加设备
  const addDevice = async (type, name, room = '客厅', properties = {}) => {
    if (!authStore.isLoggedIn.value) {
      throw new Error('请先登录')
    }
    
    state.loading = true
    state.error = null
    
    try {
      // 获取设备类型ID
      const deviceTypeId = getDeviceTypeId(type)
      
      const deviceData = {
        name,
        deviceTypeId,
        userId: authStore.user.value.id,
        room,
        ipAddress: '192.168.1.100', // 模拟IP地址
        macAddress: 'AA:BB:CC:DD:EE:FF', // 模拟MAC地址
        properties: JSON.stringify(properties)
      }
      
      const response = await deviceAPI.createDevice(deviceData)
      
      // 创建本地设备对象
      let device
      switch (type) {
        case DEVICE_TYPES.LIGHT:
          device = new LightDevice(response.id, name, room)
          break
        case DEVICE_TYPES.AIR_CONDITIONER:
          device = new AirConditionerDevice(response.id, name, room)
          break
        case DEVICE_TYPES.CURTAIN:
          device = new CurtainDevice(response.id, name, room)
          break
        case DEVICE_TYPES.CAMERA:
          device = new CameraDevice(response.id, name, room)
          break
        default:
          throw new Error('未知设备类型')
      }
      
      // 设置属性
      Object.assign(device, properties)
      
      // 确保设备对象完整
      if (device && device.type && device.id) {
        state.devices.push(device)
        
        // 记录添加设备活动
        addActivity(`已添加设备：${name}（${room}）`, 'success')
      }
      
      return device
    } catch (error) {
      state.error = error.message
      throw error
    } finally {
      state.loading = false
    }
  }
  
  // 获取设备类型ID
  const getDeviceTypeId = (type) => {
    const typeMap = {
      [DEVICE_TYPES.LIGHT]: 1,
      [DEVICE_TYPES.AIR_CONDITIONER]: 2,
      [DEVICE_TYPES.CURTAIN]: 3,
      [DEVICE_TYPES.CAMERA]: 4
    }
    return typeMap[type] || 1
  }
  
  // 删除设备
  const removeDevice = async (id) => {
    try {
      await deviceAPI.deleteDevice(id)
      const index = state.devices.findIndex(device => device.id === id)
      if (index > -1) {
        state.devices.splice(index, 1)
      }
    } catch (error) {
      state.error = error.message
      throw error
    }
  }
  
  // 更新设备状态
  const updateDeviceStatus = async (id, status) => {
    try {
      const device = state.devices.find(d => d.id === id)
      if (device) {
        const controlData = {
          userId: authStore.user.value.id,
          status: status === DEVICE_STATUS.ON ? 1 : 0,
          action: status === DEVICE_STATUS.ON ? '开启' : '关闭'
        }
        
        console.log('发送设备控制请求:', {
          deviceId: id,
          controlData: controlData
        })
        
        await deviceAPI.controlDevice(id, controlData)
        device.status = status
        console.log('设备状态更新成功')
        
        // 记录活动
        const statusText = status === DEVICE_STATUS.ON ? '开启' : '关闭'
        addActivity(`${device.name}已${statusText}`, status === DEVICE_STATUS.ON ? 'success' : 'info')
      }
    } catch (error) {
      console.error('设备控制失败:', error)
      console.error('控制参数:', {
        deviceId: id,
        status: status,
        userId: authStore.user.value.id
      })
      
      // 如果是API错误，仍然更新本地状态以提供良好的用户体验
      if (error.message.includes('HTTP 404')) {
        console.warn('设备不存在，移除本地缓存并刷新列表')
        const idx = state.devices.findIndex(d => d.id === id)
        if (idx > -1) state.devices.splice(idx, 1)
        return
      }
      if (error.message.includes('HTTP 400')) {
        state.error = '请求参数错误，请检查输入信息'
        console.warn(state.error)
        return
      }
      if (error.message.includes('HTTP 500')) {
        console.log('API控制失败，使用本地状态更新')
        const device = state.devices.find(d => d.id === id)
        if (device) {
          device.status = status
        }
        // 不抛出错误，让用户界面正常响应
        return
      }
      
      state.error = error.message
      throw error
    }
  }
  
  // 更新设备属性
  const updateDeviceProperty = async (id, property, value) => {
    try {
      const device = state.devices.find(d => d.id === id)
      if (device) {
        device[property] = value
        
        // 构建属性对象
        const properties = {}
        if (device.type === DEVICE_TYPES.LIGHT) {
          properties.brightness = device.brightness
          properties.color = device.color
        } else if (device.type === DEVICE_TYPES.AIR_CONDITIONER) {
          properties.temperature = device.temperature
          properties.mode = device.mode
          properties.fanSpeed = device.fanSpeed
        } else if (device.type === DEVICE_TYPES.CURTAIN) {
          properties.position = device.position
        }
        
        console.log('更新设备属性:', {
          deviceId: id,
          property: property,
          value: value,
          properties: properties
        })
        
        await deviceAPI.updateDeviceProperties(id, JSON.stringify(properties))
        console.log('设备属性更新成功')
        
        // 记录属性更新活动
        if (device.type === DEVICE_TYPES.LIGHT && property === 'brightness') {
          addActivity(`${device.name}亮度调节至${value}%`, 'primary')
        } else if (device.type === DEVICE_TYPES.AIR_CONDITIONER && property === 'temperature') {
          addActivity(`${device.name}温度调节至${value}°C`, 'primary')
        } else if (device.type === DEVICE_TYPES.CURTAIN && property === 'position') {
          addActivity(`${device.name}位置调节至${value}%`, 'primary')
        } else if (device.type === DEVICE_TYPES.LIGHT && property === 'color') {
          addActivity(`${device.name}颜色已更改`, 'primary')
        }
      }
    } catch (error) {
      console.error('设备属性更新失败:', error)
      
      // 如果是API错误，仍然保持本地状态更新
      if (error.message.includes('HTTP 404')) {
        console.warn('设备不存在，移除本地缓存并刷新列表')
        const idx = state.devices.findIndex(d => d.id === id)
        if (idx > -1) state.devices.splice(idx, 1)
        return
      }
      if (error.message.includes('HTTP 400')) {
        state.error = '请求参数错误，请检查输入信息'
        console.warn(state.error)
        return
      }
      if (error.message.includes('HTTP 500')) {
        console.log('API属性更新失败，保持本地状态')
        // 不抛出错误，让用户界面正常响应
        return
      }
      
      state.error = error.message
      throw error
    }
  }

  // （删除）与客厅同步功能已移除
  
  // 切换设备开关状态
  const toggleDevice = async (id) => {
    const device = state.devices.find(d => d.id === id)
    if (device) {
      const newStatus = device.status === DEVICE_STATUS.ON 
        ? DEVICE_STATUS.OFF 
        : DEVICE_STATUS.ON
      await updateDeviceStatus(id, newStatus)
    }
  }
  
  // 按房间分组设备
  const devicesByRoom = computed(() => {
    const grouped = {}
    state.devices.forEach(device => {
      if (!grouped[device.room]) {
        grouped[device.room] = []
      }
      grouped[device.room].push(device)
    })
    return grouped
  })
  
  // 按类型分组设备
  const devicesByType = computed(() => {
    const grouped = {}
    state.devices.forEach(device => {
      if (!grouped[device.type]) {
        grouped[device.type] = []
      }
      grouped[device.type].push(device)
    })
    return grouped
  })
  
  // 获取开启的设备数量
  const activeDevicesCount = computed(() => {
    return state.devices.filter(device => device.status === DEVICE_STATUS.ON).length
  })
  
  // 场景模式切换
  const setSceneMode = async (scene) => {
    console.log('切换场景模式:', scene, '当前场景:', state.currentScene)
    state.currentScene = scene
    console.log('场景模式已更新:', state.currentScene)
    await applySceneMode(scene)
    
    // 记录场景切换活动
    const sceneNames = {
      'home': '在家模式',
      'away': '离家模式', 
      'sleep': '睡眠模式',
      'party': '聚会模式'
    }
    addActivity(`已切换到${sceneNames[scene] || scene}`, 'warning')
    console.log('场景切换完成:', state.currentScene)
  }
  
  // 应用场景模式
  const applySceneMode = async (scene) => {
    const promises = []
    
    switch (scene) {
      case SCENE_MODES.AWAY:
        // 离家模式：关闭所有设备
        state.devices.forEach(device => {
          device.status = DEVICE_STATUS.OFF
          promises.push(deviceAPI.controlDevice(device.id, { 
            userId: authStore.user.value.id,
            status: 0,
            action: "关闭"
          }))
        })
        break
        
      case SCENE_MODES.SLEEP:
        // 睡眠模式：关闭灯光，调节空调
        state.devices.forEach(device => {
          if (device.type === DEVICE_TYPES.LIGHT) {
            device.status = DEVICE_STATUS.OFF
            promises.push(deviceAPI.controlDevice(device.id, { 
              userId: authStore.user.value.id,
              status: 0,
              action: "关闭"
            }))
          } else if (device.type === DEVICE_TYPES.AIR_CONDITIONER) {
            device.status = DEVICE_STATUS.ON
            device.temperature = 24
            promises.push(deviceAPI.controlDevice(device.id, { 
              userId: authStore.user.value.id,
              status: 1,
              action: "开启"
            }))
            promises.push(deviceAPI.updateDeviceProperties(device.id, JSON.stringify({ temperature: 24 })))
          }
        })
        break
        
      case SCENE_MODES.PARTY:
        // 聚会模式：开启所有灯光，调节空调
        state.devices.forEach(device => {
          if (device.type === DEVICE_TYPES.LIGHT) {
            device.status = DEVICE_STATUS.ON
            device.brightness = 100
            promises.push(deviceAPI.controlDevice(device.id, { 
              userId: authStore.user.value.id,
              status: 1,
              action: "开启"
            }))
            promises.push(deviceAPI.updateDeviceProperties(device.id, JSON.stringify({ brightness: 100 })))
          } else if (device.type === DEVICE_TYPES.AIR_CONDITIONER) {
            device.status = DEVICE_STATUS.ON
            device.temperature = 22
            promises.push(deviceAPI.controlDevice(device.id, { 
              userId: authStore.user.value.id,
              status: 1,
              action: "开启"
            }))
            promises.push(deviceAPI.updateDeviceProperties(device.id, JSON.stringify({ temperature: 22 })))
          }
        })
        break
        
      case SCENE_MODES.HOME:
      default:
        // 在家模式：保持当前状态
        break
    }
    
    // 并发执行所有API调用，但不阻塞UI
    if (promises.length > 0) {
      try {
        await Promise.allSettled(promises)
        console.log(`场景模式 ${scene} 已应用到后端`)
      } catch (error) {
        console.error('应用场景模式到后端时出错:', error)
        // 不抛出错误，保持UI响应性
      }
    }
  }
  
  // 一键关闭所有设备
  const turnOffAllDevices = async () => {
    // 先更新前端状态，立即响应用户
    state.devices.forEach(device => {
      device.status = DEVICE_STATUS.OFF
    })
    
    // 并发调用后端API
    const promises = state.devices.map(device => 
      deviceAPI.controlDevice(device.id, { 
        userId: authStore.user.value.id,
        status: 0, // 0=关闭
        action: "关闭"
      })
    )
    
    try {
      await Promise.allSettled(promises)
      console.log('所有设备已关闭并同步到后端')
      addActivity('已关闭所有设备', 'info')
    } catch (error) {
      console.error('关闭设备时出错:', error)
      // 不抛出错误，保持UI响应性
    }
  }
  
  // 一键开启所有设备
  const turnOnAllDevices = async () => {
    // 先更新前端状态，立即响应用户
    state.devices.forEach(device => {
      device.status = DEVICE_STATUS.ON
    })
    
    // 并发调用后端API
    const promises = state.devices.map(device => 
      deviceAPI.controlDevice(device.id, { 
        userId: authStore.user.value.id,
        status: 1, // 1=开启
        action: "开启"
      })
    )
    
    try {
      await Promise.allSettled(promises)
      console.log('所有设备已开启并同步到后端')
      addActivity('已开启所有设备', 'success')
    } catch (error) {
      console.error('开启设备时出错:', error)
      // 不抛出错误，保持UI响应性
    }
  }
  
  // 清除错误状态
  const clearError = () => {
    state.error = null
  }
  
  // 模拟设备数据方法已移除，只使用真实后端数据

  // 真实设备控制方法
  const controlRealDevice = async (deviceId, commandType, value, parameters = {}) => {
    try {
      const commandData = {
        commandType,
        value,
        userId: authStore.user.value.id,
        action: `${commandType}控制`,
        parameters
      }
      
      const result = await realDeviceAPI.controlDevice(deviceId, commandData)
      
      // 更新本地设备状态
      const device = state.devices.find(d => d.id === deviceId)
      if (device) {
        if (commandType === 'switch') {
          device.status = value ? DEVICE_STATUS.ON : DEVICE_STATUS.OFF
        }
        if (parameters.brightness !== undefined) {
          device.brightness = parameters.brightness
        }
        if (parameters.temperature !== undefined) {
          device.temperature = parameters.temperature
        }
        if (parameters.color !== undefined) {
          device.color = parameters.color
        }
      }
      
      addActivity(`设备${device?.name || deviceId}执行${commandType}控制`, 'success')
      return result
    } catch (error) {
      console.error('真实设备控制失败:', error)
      state.error = error.message
      addActivity(`设备${deviceId}控制失败：${error.message}`, 'danger')
      throw error
    }
  }

  // 智能灯光控制
  const controlSmartLight = async (deviceId, action, value) => {
    try {
      const userId = authStore.user.value.id
      let result
      
      if (action === 'switch') {
        result = await smartLightAPI.switchLight(deviceId, value, userId)
      } else if (action === 'brightness') {
        result = await smartLightAPI.setBrightness(deviceId, value, userId)
      }
      
      // 更新本地设备状态
      const device = state.devices.find(d => d.id === deviceId)
      if (device) {
        if (action === 'switch') {
          device.status = value ? DEVICE_STATUS.ON : DEVICE_STATUS.OFF
        } else if (action === 'brightness') {
          device.brightness = value
        }
      }
      
      addActivity(`智能灯光${device?.name || deviceId}执行${action}控制`, 'success')
      return result
    } catch (error) {
      console.error('智能灯光控制失败:', error)
      state.error = error.message
      addActivity(`智能灯光${deviceId}控制失败：${error.message}`, 'danger')
      throw error
    }
  }

  // 智能温控器控制
  const controlSmartThermostat = async (deviceId, temperature) => {
    try {
      const userId = authStore.user.value.id
      const result = await smartThermostatAPI.setTemperature(deviceId, temperature, userId)
      
      // 更新本地设备状态
      const device = state.devices.find(d => d.id === deviceId)
      if (device) {
        device.temperature = temperature
      }
      
      addActivity(`智能温控器${device?.name || deviceId}设置温度${temperature}°C`, 'success')
      return result
    } catch (error) {
      console.error('智能温控器控制失败:', error)
      state.error = error.message
      addActivity(`智能温控器${deviceId}控制失败：${error.message}`, 'danger')
      throw error
    }
  }

  // 获取设备实时状态
  const getDeviceRealTimeStatus = async (deviceId) => {
    try {
      const result = await realDeviceAPI.getDeviceStatus(deviceId)
      addActivity(`获取设备${deviceId}实时状态`, 'info')
      return result
    } catch (error) {
      console.error('获取设备状态失败:', error)
      state.error = error.message
      throw error
    }
  }

  // 检查设备在线状态
  const checkDeviceOnline = async (deviceId) => {
    try {
      const result = await realDeviceAPI.checkDeviceOnline(deviceId)
      return result
    } catch (error) {
      console.error('检查设备在线状态失败:', error)
      return { online: false }
    }
  }

  // 同步设备状态
  const syncDeviceStatus = async (deviceId) => {
    try {
      const result = await deviceStatusAPI.syncDeviceStatus(deviceId)
      addActivity(`同步设备${deviceId}状态`, 'info')
      return result
    } catch (error) {
      console.error('同步设备状态失败:', error)
      state.error = error.message
      throw error
    }
  }

  // 批量同步设备状态
  const batchSyncDeviceStatus = async (deviceIds) => {
    try {
      const result = await deviceStatusAPI.batchSyncDeviceStatus(deviceIds)
      addActivity(`批量同步${deviceIds.length}个设备状态`, 'info')
      return result
    } catch (error) {
      console.error('批量同步设备状态失败:', error)
      state.error = error.message
      throw error
    }
  }

  // 获取设备状态统计
  const getDeviceStatusStats = async () => {
    try {
      const result = await deviceStatusAPI.getDeviceStatusStats()
      return result
    } catch (error) {
      console.error('获取设备状态统计失败:', error)
      state.error = error.message
      throw error
    }
  }

  // 智能摄像头控制方法
  const controlSmartCamera = async (deviceId, action, value, parameters = {}) => {
    try {
      const userId = authStore.user.value.id
      let result
      
      switch (action) {
        case 'switch':
          result = await smartCameraAPI.switchCamera(deviceId, value, userId)
          break
        case 'record':
          result = await smartCameraAPI.controlRecording(deviceId, value, userId)
          break
        case 'snapshot':
          result = await smartCameraAPI.takePhoto(deviceId, userId, parameters)
          break
        case 'angle':
          // 先调节水平角度，再调节垂直角度
          await smartCameraAPI.adjustPan(deviceId, parameters.pan, userId)
          result = await smartCameraAPI.adjustTilt(deviceId, parameters.tilt, userId)
          break
        case 'resolution':
          result = await smartCameraAPI.setResolution(deviceId, value, userId)
          break
        case 'nightVision':
          result = await smartCameraAPI.setNightVision(deviceId, value, userId)
          break
        case 'patrol_start':
          result = await smartCameraAPI.startPatrol(deviceId, userId)
          break
        case 'patrol_stop':
          result = await smartCameraAPI.stopPatrol(deviceId, userId)
          break
        default:
          throw new Error(`不支持的摄像头操作: ${action}`)
      }
      
      // 更新本地设备状态
      const device = state.devices.find(d => d.id === deviceId)
      if (device) {
        if (action === 'switch') {
          device.status = value ? DEVICE_STATUS.ON : DEVICE_STATUS.OFF
        }
        if (action === 'recording') {
          device.recording = value === 'start'
        }
        if (action === 'nightVision') {
          device.nightVision = value
        }
        if (action === 'resolution') {
          device.resolution = value
        }
        if (action === 'patrol_start') {
          device.patrolling = true
        }
        if (action === 'patrol_stop') {
          device.patrolling = false
        }
      }
      
      addActivity(`智能摄像头${device?.name || deviceId}执行${action}控制`, 'success')
      return result
    } catch (error) {
      console.error('智能摄像头控制失败:', error)
      state.error = error.message
      addActivity(`智能摄像头${deviceId}控制失败：${error.message}`, 'danger')
      throw error
    }
  }

  // 获取摄像头状态
  const getCameraStatus = async (deviceId) => {
    try {
      const result = await smartCameraAPI.getCameraStatus(deviceId)
      addActivity(`获取摄像头${deviceId}状态`, 'info')
      return result
    } catch (error) {
      console.error('获取摄像头状态失败:', error)
      state.error = error.message
      throw error
    }
  }

  // 获取录像列表
  const getRecordingList = async (deviceId, page = 0, size = 10) => {
    try {
      const result = await smartCameraAPI.getRecordingList(deviceId, page, size)
      return result
    } catch (error) {
      console.error('获取录像列表失败:', error)
      state.error = error.message
      throw error
    }
  }

  // 获取视频流URL
  const getVideoStreamUrl = async (deviceId) => {
    try {
      const result = await smartCameraAPI.getVideoStreamUrl(deviceId)
      return result
    } catch (error) {
      console.error('获取视频流URL失败:', error)
      state.error = error.message
      throw error
    }
  }
  
  return {
    // 状态
    devices: computed(() => state.devices),
    currentScene: computed(() => state.currentScene),
    devicesByRoom,
    devicesByType,
    activeDevicesCount,
    loading: computed(() => state.loading),
    error: computed(() => state.error),
    recentActivities: computed(() => state.recentActivities),
    
    // 方法
    loadUserDevices,
    addDevice,
    removeDevice,
    updateDeviceStatus,
    updateDeviceProperty,
    toggleDevice,
    setSceneMode,
    applySceneMode,
    turnOffAllDevices,
    turnOnAllDevices,
    clearError,
    
    // 真实设备控制方法
    controlRealDevice,
    controlSmartLight,
    controlSmartThermostat,
    getDeviceRealTimeStatus,
    checkDeviceOnline,
    syncDeviceStatus,
    batchSyncDeviceStatus,
    getDeviceStatusStats,
    
    // 智能摄像头控制方法
    controlSmartCamera,
    getCameraStatus,
    getRecordingList,
    getVideoStreamUrl
  }
}
